#!/bin/bash

# 设置颜色
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

# 检查root权限
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}请使用root权限运行此脚本${NC}"
    exit 1
fi

# 设置变量
INSTALL_DIR="/opt/ollama-chat"
SERVICE_NAME="ollama-chat"
SERVICE_USER="ollama"
SERVICE_GROUP="ollama"
LOG_DIR="/var/log/ollama-chat"

# 创建用户和组
echo "创建服务用户和组..."
groupadd -f $SERVICE_GROUP
id -u $SERVICE_USER &>/dev/null || useradd -r -g $SERVICE_GROUP -s /bin/false $SERVICE_USER

# 创建目录
echo "创建必要的目录..."
mkdir -p $INSTALL_DIR
mkdir -p $LOG_DIR
mkdir -p $INSTALL_DIR/logs
mkdir -p $INSTALL_DIR/chat_sessions

# 复制文件
echo "复制应用文件..."
cp -r . $INSTALL_DIR/
cd $INSTALL_DIR

# 设置权限
echo "设置权限..."
chown -R $SERVICE_USER:$SERVICE_GROUP $INSTALL_DIR
chown -R $SERVICE_USER:$SERVICE_GROUP $LOG_DIR
chmod -R 755 $INSTALL_DIR
chmod -R 644 $LOG_DIR

# 安装依赖
echo "安装依赖..."
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pip install -e .

# 复制服务文件
echo "安装系统服务..."
cp deployment/ollama-chat.service /etc/systemd/system/

# 重载systemd
systemctl daemon-reload

# 启动服务
echo "启动服务..."
systemctl enable $SERVICE_NAME
systemctl start $SERVICE_NAME

# 检查状态
if systemctl is-active --quiet $SERVICE_NAME; then
    echo -e "${GREEN}部署完成！服务已成功启动${NC}"
    echo "可以使用以下命令查看服务状态："
    echo "systemctl status $SERVICE_NAME"
else
    echo -e "${RED}服务启动失败，请检查日志：${NC}"
    echo "journalctl -u $SERVICE_NAME"
    exit 1
fi 